package com.shuyun.classloader.jar;

import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2021/8/23 3:09 下午
 */
public class ProtocolManager {

    private static Map<String, IProtocol> protocolMap = new ConcurrentHashMap<>();

    /**
     * 读取jar，创建IProtocol的实例
     * @param jar
     * @return
     */
    public static Map<String, IProtocol> loadProtocol(URL jar) {
        try {
            JarURLClassLoader classLoader = new JarURLClassLoader(jar);
            Set<Class> classes = classLoader.loadClass("com.shuyun.open.protocol", IProtocol.class);
            if (classes != null && classes.size() > 0) {
                for (Class clazz : classes) {
                    IProtocol protocol = (IProtocol) clazz.newInstance();
                    protocolMap.put(protocol.name(), protocol);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return protocolMap;
    }

    public static IProtocol loadProtocol(URL jar, String name) throws Exception {
        JarURLClassLoader classLoader = new JarURLClassLoader(jar);
        IProtocol protocol = (IProtocol) classLoader.loadClass(name).newInstance();
        return protocol;
    }

}
